package com.tulele.vtool.task.async;

import com.tulele.vtool.bus.mapper.log.PushDetailLogMapper;
import com.tulele.vtool.bus.model.DailyPaperInfo;
import com.tulele.vtool.bus.model.UserInfo;
import com.tulele.vtool.bus.model.UserVipValidInfo;
import com.tulele.vtool.bus.model.log.PushDetailLog;
import com.tulele.vtool.bus.model.thirdparty.WxNotifyMsgSetInfo;
import com.tulele.vtool.bus.service.IUserService;
import com.tulele.vtool.bus.service.IUserVipValidService;
import com.tulele.vtool.bus.service.SysGzhService;
import com.tulele.vtool.model.PlatformSysInfo;
import com.tulele.vtool.util.DateUtil;
import com.tulele.vtool.util.SpringContextUtil;
import com.tulele.vtool.wechat.service.WeixinService;
import com.tulele.vtool.wechat.service.WeixinServiceDL;
import com.tulele.vtool.wechat.service.WeixinServiceMap;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Optional;

//离服务到期时间还有3、7天的推送
@Component
@Slf4j
public class ExpirationReminderTempMsgAsyncTask {

    @Autowired
    private ObjectFactory<WeixinServiceDL> objectFactory;

    @Autowired
    private SysGzhService sysGzhService;

//    @Value("${customerMenuUrl}")
//    private String customerMenuUrl;
//
//    @Value("${expirationReminderTempID}")
//    private String expirationReminderTempID;
//
//    @Value("${openMemberMenuUrl}")
//    private String openMemberMenuUrl;

    @Autowired
    private IUserVipValidService userVipValidService;

    @Autowired
    private PushDetailLogMapper pushDetailLogMapper;


    //20200504 yl 改成同步发 因为多线程 数据库顶不住
    //20200512 调整参数，多线程跑
    @Async("taskExecutor")
    public Integer execute(UserInfo user, Integer headId, String profile) {

        Integer ret = 2;

        if (user.getOpenId() != null) {
            // 发送模板消息接口
            PlatformSysInfo sysGzh = sysGzhService.getPlatformSysInfo(profile);
            WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                    // 接收者openid
                    .toUser(user.getOpenId())
                    // 模板id
                    .templateId(sysGzh.getSysGzh().getExpirationReminderTempId())
                    // 模板跳转链接
                    .url(sysGzh.getOpenMemberMenuUrl() + "?mt=1&cardBag=1")
                    .build();
            String firstMsg = user.getNickName() + "老师，您的高级会员即将到期，会员过期后您将不能管理客户信息等高级会员功能权限，请及时续费升级！\n\n";
            String remarkMsg = "【点击】续费 最高30元优惠券（限时）\n\n";

            // 添加模板数据
            templateMessage.addData(new WxMpTemplateData("first", firstMsg, "#FF00FF"))
                    .addData(new WxMpTemplateData("keyword1", user.getGzhName(), "#A9A9A9"))
                    .addData(new WxMpTemplateData("keyword2", DateUtil.getFormatDate("yyyy-MM-dd", user.getEndTime()), "#A9A9A9"))
                    .addData(new WxMpTemplateData("keyword3", "0", "#A9A9A9"))
                    .addData(new WxMpTemplateData("remark", remarkMsg, "#FF0000"));

            PushDetailLog pushDetailLog = new PushDetailLog();
            pushDetailLog.setGzhCode(profile);
            pushDetailLog.setUserId(user.getUserId());
            pushDetailLog.setMsgType(11);//到期
            pushDetailLog.setPushTime(new Date());
            pushDetailLog.setHeadId(headId);
            pushDetailLog.setOpenId(user.getOpenId());

            try {
                // 发送模板消息
                WeixinServiceDL weixinService = WeixinServiceMap.getWeixinService(profile);
                if (weixinService == null) {
                    weixinService = objectFactory.getObject();
                    weixinService.reSetConfigStorage(profile);
                    WeixinServiceMap.putWeixinService(profile, weixinService);
                }
                weixinService.getTemplateMsgService().sendTemplateMsg(templateMessage);
                ret = 0;
                pushDetailLog.setMsg("成功");
            } catch (WxErrorException e) {
                ret = 2;
                pushDetailLog.setMsg(e.getMessage());
            }

            pushDetailLog.setResult(ret);

            pushDetailLogMapper.addPushDetailLog(pushDetailLog);

        }
        return ret;
    }
}
